package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Volatile不保证原子性
 */
public class VolatileDemo {
    
    private static AtomicInteger num = new AtomicInteger();
    private volatile static int a = 0;
    public static void add(){
        num.getAndIncrement();
    }
    public static void main(String[] args) throws InterruptedException {
        for (int i = 1; i <= 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    add();
                }
                while (a == 0){
                    
                }
            }).start();
        }

        TimeUnit.SECONDS.sleep(1);
        a = 1;
//        while (Thread.activeCount() > 2){
//            Thread.yield();
//        }
        System.out.println(num);
    }
}
